<template>
	<view class="quesDetail">
		<!-- #ifdef APP-PLUS || MP-WEIXIN -->
		<!-- <view class="customHeight"></view> -->
		<!-- #endif -->
		<!-- #ifdef APP-PLUS || H5 -->
		<uni-mdnav :title="`提问详情页`" fixed ref="mdNav" leftIcon="left" rightIcon="notification" :border="true"></uni-mdnav>
		<!-- #endif -->
		<!-- #ifdef MP-WEIXIN -->
		<uni-mdnav :title="`提问详情页`" ref="mdNav" leftIcon="left" :border="true"></uni-mdnav>
		<!-- #endif -->
		<!-- 关于提问 -->
		<view class="aboutQues" v-if="quesInfo">
			<!-- 相关任务 -->
			<view class="quesTask flex alignCenter" v-if="quesInfo.taskId>0" @click.stop="toTask">
				<view class="topic font10">任务</view>
				<view class="font14 hiddenOneline">{{quesInfo.taskTitle}}</view>
			</view>
			<!-- 提问标题 -->
			<view class="flex alignCenter justConBetween quesTitle">
				<view class="titleArea bold font16">
					<image v-if="quesInfo.bounty>0" class="" src="@/static/image/icons/b.png" mode="widthFix"></image>
					<text v-if="quesInfo.bounty>0" class="bold colorRed">￥{{quesInfo.bounty}}</text>
					{{quesInfo.title}}
				</view>
				<uni-icons v-if="isMine" class="del" type="closeempty" size="20" @click="delQuestion"></uni-icons>
			</view>
			
			<view class="avatar flex alignCenter justConBetween">
				<!-- <view class="posTag font10">
					<image src="@/static/image/icons/tag.png" mode="widthFix"></image>
					<text class="bold">{{quesInfo.type==1?'图文':(quesInfo.type==2?'音频':'视频')}}</text>
				</view> -->
				<view class="flex alignCenter">
					<view class="quesAva">
						<image src="https://image.alhelp.net/uploads/20231104/4d491857ac50d21ebbcb25ff5bc254f8.png" mode="widthFix"></image>
						<!-- <view class="focus" v-if="!quesInfo.isLikedUser" @click.stop="focusClick('creater')">+</view> -->
					</view>
					<view class="">
						<view class="font14 bold">{{quesInfo.createUserName || '匿名用户'}}</view>
						<view class="colorccc font12">{{quesInfo.createTime}}</view>
					</view>
				</view>
				<view class="focus bold font12" v-if="(!quesInfo.isLikedUser && !isMine)" @click.stop="focusClick('creater')">+关注</view>
			</view>
			<!-- 提问内容 -->
			<view class="quesCon">
				<view class="quesTxt" v-html="quesInfo.content">{{quesInfo.content}}</view>
				<view class="" v-if="quesInfo.imgUrl">
					<uni-imgbox :canDel="false" :imgArr="quesInfo.imgUrl.split(',')"></uni-imgbox>
				</view>
				<!-- <view class="richBox" v-if="quesInfo.type==1">
					<rich-text :nodes="quesInfo.goodNodes"></rich-text>
				</view> -->
				<!-- <view class="audioBox" v-if="quesInfo.type==2">
					<audio controls :name="'测试音屏'" :author="'小小毛'" :poster="`https://web-assets.dcloud.net.cn/unidoc/zh/music-a.png`" src="https://bjetxgzv.cdn.bspapp.com/VKCEYUGU-hello-uniapp/2cc220e0-c27a-11ea-9dfb-6da8e309e0d8.mp3"></audio>
				</view> -->
				<!-- <view class="videoBox" v-if="quesInfo.type==3">
					<video controls src="https://img.cdn.aliyun.dcloud.net.cn/guide/uniapp/%E7%AC%AC1%E8%AE%B2%EF%BC%88uni-app%E4%BA%A7%E5%93%81%E4%BB%8B%E7%BB%8D%EF%BC%89-%20DCloud%E5%AE%98%E6%96%B9%E8%A7%86%E9%A2%91%E6%95%99%E7%A8%8B@20200317.mp4"></video>
				</view> -->
			</view>
		</view>
		<!-- 最佳答案 可以是图文，可以是视频 -->
		<view class="bestAnswer" v-if="quesInfo.bestAnswerId>-1">
			<view class="font16 bold bestTitle flex alignCenter">
				<view class="">选中的答案</view>
			</view>
			<view class="answerAvatar flex alignCenter justConBetween">
				<view class="flex alignCenter">
					<view class="quesAva">
						<image :src="quesInfo.bestUserAvatar ||'https://image.alhelp.net/uploads/20231104/4d491857ac50d21ebbcb25ff5bc254f8.png'" mode="widthFix"></image>
						<!-- <view class="focus" @click.stop="focusClick('bestAnswer')">+</view> -->
					</view>
					<view class="font14 bold">{{quesInfo.bestUserName || '匿名回答者'}}</view>
				</view>
				<view class="noWidthBtn flex alignCenter" @click.stop="toBestAnswer">
					<image class="focusMargin" src="@/static/image/icons/eye.png" mode="widthFix"></image>
					看答案
				</view>
			</view>
		</view>
		<!-- 回答 可以是图文，可以是视频 -->
		<view class="answer" v-if="answerArr.length>0">
			<!-- 做了吸顶但是有问题 -->
			<view :class="canFixed?'answerTitle fixedTop':'answerTitle'" id="scrollNode" ref="scrollNode">
				<view class="bold font16 txt">回答<text class="mathMagrin">{{answerArr.length}}</text></view>
				<!-- <text class="font14">{{answerArr.length}}</text> -->
			</view>
			<!-- <view class="answerTitle" id="scrollNode" ref="scrollNode">
				<text class="bold font16 txt">回答</text>
				<text class="font14">{{answerArr.length}}</text>
			</view> -->
			<view class="ansList">
				<template v-for="(item,index) in answerArr">
					<uni-answer :key="index" :quesBounty="quesInfo.bounty" :answerItem="item" :quesId="quesId" :canChooseBest="(quesInfo.bestAnswerId==-1 && isMine)?true:false" :quesTitle="quesInfo.title" @chooseBestSucc="chooseBestSucc" @answerOper="answerOper"></uni-answer>
				</template>
			</view>
		</view>
		<cover-view class="flex alignCenter justConAround fixBottom">
			<cover-view class="flex alignCenter" @click.stop="shareClick">
				<cover-image src="https://image.alhelp.net/uploads/20231104/db05a877babde8bbcce75893aced0760.png" mode="widthFix"></cover-image>
				<cover-view class="txt" @click.stop="shareClick">邀请回答</cover-view>
			</cover-view>
			<cover-view class="line"></cover-view>
			<cover-view class="flex alignCenter" @click.stop="writeAnswer">
				<cover-image src="@/static/image/icons/edit.png" mode="widthFix" @click.stop="writeAnswer"></cover-image>
				<cover-view class="txt" @click.stop="writeAnswer">写答案</cover-view>
			</cover-view>
		</cover-view>
		<!-- 三点操作 -->
		<!-- #ifndef H5 -->
		
		<dotoper :dotOperShow="dotOperShow" @cancelOper="cancelOper" @chooseDotOper="delQuestion"></dotoper>
		<!-- #endif -->
		<!-- #ifdef H5 -->
		<uni-dotoper :dotOperShow="dotOperShow" @cancelOper="cancelOper" @chooseDotOper="delQuestion"></uni-dotoper>
		<!-- #endif -->
		<uni-login @closeLogin="closeLogin" :loginShow="isLoading"></uni-login>
	</view>
</template>

<script>
	import { delQues,quesDetail,answerListByQues } from "@/api/send.js" 
	import { bestAnswer } from "@/api/school.js"
	import { focusUser } from "@/api/index.js"
	import { payBeforeTip,navigateLoginPage } from "@/utils/common.js"
	import dotoper from "@/pages/send/components/dotoper.nvue"
	import uniAnswer from "@/pages/send/components/uni-answer/uni-answer.vue"
	import uniLogin from '@/components/uni-login/uni-login.vue'
	export default {
		components:{
			dotoper,
			uniAnswer,
			uniLogin
		},
		data() {
			return {
				isLoading:false,
				quesId:'',
				dotOperShow:false,
				quesInfo:'',
				answerArr:[],
				nodeScrollTop:'',
				canFixed:false,
				isMine:false,
				page:1,
				pageSize:10,
				pageTotal:0,
				previewImg:false,//用来解决预览图片会导致执行onShow生命周期的问题
				answerTotalNum:0,
			};
		},
		onLoad(option) {
			// console.log('option',JSON.parse(option.item))
			this.removePreviewImg()
			// 只有首页推荐列表才有questionId（打卡笔记type==5的时候是-1），热点没有该字段
			this.quesId=(JSON.parse(option.item).questionId && JSON.parse(option.item).questionId!=-1)?JSON.parse(option.item).questionId:JSON.parse(option.item).id 
			// this.dealListData()
		},
		onShow() {
			// #ifdef APP-PLUS || H5
			this.$nextTick(()=>{
				this.$refs.mdNav.reFresh()
			})
			// #endif
			this.getDetail()
			this.previewImg=uni.getStorageSync('previewImg') || false
			if(this.previewImg) return
			this.initPage()
			this.getAnswerList()
			
			// 计算回答定位的高度
			this.$nextTick(()=>{
				setTimeout(()=>{
					if(this.answerArr.length==0) return;
					this.getNodeScrollTop('#scrollNode')
				},200)
			})
		},
		onReady() {
			// 计算回答定位的高度
			this.$nextTick(()=>{
				setTimeout(()=>{
					if(this.answerArr.length==0) return;
					this.getNodeScrollTop('#scrollNode')
				},200)
			})
		},
		onUnload() {
			this.removePreviewImg()
		},
		methods:{
			closeLogin(){
				this.isLoading = false;
			},
			initPage(){
				this.page=1;
				this.answerArr=[];
			},
			// 清空预览图片标识
			removePreviewImg(){
				uni.removeStorageSync('previewImg')
			},
			//提问详情
			getDetail(){
				uni.showLoading({
					title:'加载中',
					mask:true
				})
				quesDetail({id:this.quesId}).then((res)=>{
					uni.hideLoading()
					if(res.code==100000){
						this.quesInfo=res.data
						this.isMine=(this.quesInfo.createUserId==uni.getStorageSync('userId')?true:false)
						// 最佳答案
						// this.bestAnswer={
						// 	createUserAvatar:this.quesInfo.bestUserAvatar,
						// 	createUserName:this.quesInfo.bestUserName,
						// 	createTime:this.quesInfo.createTime || '',
						// 	content:this.quesInfo.bestAnswerContent,
						// 	imgUrl:'',
						// 	videoUrl:''
						// }
						
					}
				}).catch((err)=>{uni.hideLoading()})
			},
			// 回答列表
			getAnswerList(){
				let param={
					page:this.page,
					size:this.pageSize,
					questionId:this.quesId
				}
				answerListByQues(param).then((res)=>{
					if(res.code==100000){
						this.answerArr=res.data.rows
						this.answerTotalNum=res.data.total?res.data.total:0
						this.pageTotal=Math.ceil(res.data.total/this.pageSize)
						if(this.answerArr.length==0) return;
						// 计算回答定位的高度
						// this.$nextTick(()=>{
						// 	this.getNodeScrollTop('#scrollNode')
						// })
					}
				})
			},
			// 任务详情
			toTask(){
				uni.navigateTo({
					url:'/pages/send/task/taskDetail/taskDetail?id='+this.quesInfo.taskId
				})
			},
			// 删除提问（仅限本人提问）
			delQuestion(){
				uni.showModal({
					title: '提示',
					content: '确定删除该提问吗？',
					success:(res)=> {
						if (res.confirm) {
							delQues({id:this.quesInfo.id}).then((res)=>{
								if(res.code==100000){
									uni.showToast({
										title:'删除成功',
										icon:'none'
									})
									setTimeout(()=>{
										uni.navigateBack({
											delta:1
										})
									},1000)
								}
							})
						} else if (res.cancel) {}
					}
				});
			},
			// 展示操作
			showDot(){
				this.dotOperShow=true
				
			},
			// 删除提问（仅限本人提问）
			// delQuestion(oper){
			// 	if(oper.id==3){
			// 		uni.showModal({
			// 			title: '提示',
			// 			content: '确定删除该提问吗？',
			// 			success:(res)=> {
			// 				if (res.confirm) {
			// 					delQues({id:this.quesInfo.id}).then((res)=>{
			// 						if(res.code==100000){
			// 							uni.showToast({
			// 								title:'删除成功',
			// 								icon:'none'
			// 							})
			// 							setTimeout(()=>{
			// 								uni.navigateBack({
			// 									delta:1
			// 								})
			// 							},1000)
			// 						}
			// 					})
			// 				} else if (res.cancel) {}
			// 			}
			// 		});
			// 	}
			// },
			// 隐藏三点操作
			cancelOper(){
				this.dotOperShow=false
				// uni.redirectTo({
				// 	url:`/pages/send/question/questionDetail/questionDetail?item=${JSON.stringify(this.quesInfo)}`
				// })
			},
			// 分享
			shareClick(){
				if(!uni.getStorageSync('token')){
					// #ifdef MP-WEIXIN
					this.isLoading = true;
					// #endif
					// #ifndef MP-WEIXIN
					navigateLoginPage()
					// #endif
					return
				}
				// inviteType 1提问者邀请；2最佳回答者邀请；3普通用户的提问邀请；4邀请加入小组；5任务打卡邀请
				let inviteType=''
				if(this.quesInfo.createUserId==uni.getStorageSync('userId')){
					inviteType=1
				}else if(this.quesInfo.bestUserId==uni.getStorageSync('userId')){
					inviteType=2
				}else{
					inviteType=3
				}
				let query={
					id:this.quesInfo.id,
					questionId:this.quesInfo.questionId,
					inviteType:inviteType
				}
				uni.navigateTo({
					url:'/pages/school/share/share?query='+JSON.stringify(query)
				})
			},
			// 写答案
			writeAnswer(){
				console.error('写答案')
				if(!uni.getStorageSync('token')){
					// #ifdef MP-WEIXIN
					this.isLoading = true;
					// #endif
					// #ifndef MP-WEIXIN
					navigateLoginPage()
					// #endif
					return
				}
				this.removePreviewImg()
				let query={
					id:this.quesId,
					title:this.quesInfo.title
				}
				uni.navigateTo({
					url:'/pages/send/answer/answer?query='+JSON.stringify(query)
				})
			},
			// 选择为最佳答案
			chooseBestSucc(answerId){
				if(this.quesInfo.bounty>0){
					let query={
						type:3,
						money:this.quesInfo.bounty,
						id:answerId,
						quesTitle:this.quesInfo.title
					}
					uni.navigateTo({
						url:`/pages/order/order?query=${JSON.stringify(query)}`
					})
				}else{
					this.getDetail()
					this.initPage()
					this.getAnswerList()
				}
			},
			// 回答的操作（用户关注）
			answerOper(obj){
				if(obj.type=='focus'){
					this.answerArr.forEach((item)=>{
						if(obj.userId==item.createUserId){
							item.stateField.isLikedUser=obj.status
						}
					})
				}
			},
			dealListData(){
				this.answerArr.forEach((item)=>{
					if(item.nodes){
						let param={
							name:'div',
							children:[]
						}
						item.nodes.forEach((item2)=>{
							if(item2.type=='text'){
								param.children.push({
									type:'text',
									text:item2.content
								})
							}
							if(item2.type=='image'){
								param.children.push({
									name:'img',
									attrs:{
										src:item2.url,
										style: 'width:100%'
									}
								})
							}
							item.goodNodes=[param]
						})
					}
				})
			},
			getNodeScrollTop(node){
				let _this=this
				const query = uni.createSelectorQuery().in(this)
				query.select(node).boundingClientRect()
				query.selectViewport().scrollOffset()
				query.exec(function(res){
					_this.nodeScrollTop=res[0].top || 0
					console.log("得到布局位置信息" ,res,_this.nodeScrollTop);
				})
			},
			// 去回答详情页
			// toDetail(){
			// 	this.removePreviewImg()
			// 	uni.navigateTo({
			// 		url:`/pages/send/answer/answerDetail/answerDetail?id=${this.quesInfo.bestAnswerId}&quesTitle=${this.quesInfo.title}`
			// 	})
			// },
			// 查看最佳答案
			toBestAnswer(){
				// // 如果最佳回答是自己，或者提问的是自己则不需要付钱
				// if(this.isMine || this.quesInfo.bestUserId==uni.getStorageSync('userId')){
				// 	uni.navigateTo({
				// 		url:`/pages/send/answer/answerDetail/answerDetail?id=${this.quesInfo.bestAnswerId}&quesTitle=${this.quesInfo.title}`
				// 	})
				// }else{
				// 	//支付一元查看，提问和最佳回答各分一半，isBestBuy 是来判断需不需要给钱的
				// 	let isBestBuy=(this.isMine || this.quesInfo.bestUserId==uni.getStorageSync('userId'))
				// 	let param={
				// 		id:this.quesInfo.bestAnswerId,
				// 		isBestBuy:isBestBuy,//this.quesInfo.isBestBuy,
				// 		quesTitle:this.quesInfo.title
				// 	}
				// 	payBeforeTip(param)
				// }
				//支付一元查看，提问和最佳回答各分一半，isBestBuy 是来判断需不需要给钱的
				// let isBestBuy=(this.isMine || this.quesInfo.bestUserId==uni.getStorageSync('userId'))
				let param={
					id:this.quesInfo.bestAnswerId,
					isBestBuy:this.quesInfo.isBestBuy,
					quesTitle:this.quesInfo.title
				}
				payBeforeTip(param)
			},
			// 关注事件
			focusClick(user){
				if(user=='creater'){
					if(this.quesInfo.createUserId==uni.getStorageSync('userId')){
						uni.showToast({
							title:'亲，这是你自己哦',
							icon:'none'
						})
						return
					}
					let param={
						isAdd:!this.quesInfo.isLikedUser,
						fansUserId:this.quesInfo.createUserId,
						fansUserName:this.quesInfo.createUserName,
						fansUserAvatar:this.quesInfo.createUserAvatar,
					}
					focusUser(param).then((res)=>{
						if(res.code==100000){
							this.quesInfo.isLikedUser=!this.quesInfo.isLikedUser
						}
					})
					return
				}else if(user=='bestAnswer'){
					if(this.quesInfo.bestUserId==uni.getStorageSync('userId')){
						uni.showToast({
							title:'亲，这是你自己哦',
							icon:'none'
						})
						return
					}
					uni.showToast({
						title:'关注最佳回答者',
						icon:'none'
					})
					//TO DO 关注最佳回答者
				}
			}
		},
		onPullDownRefresh() {
			this.initPage()
			this.getDetail()
			this.getAnswerList()
			setTimeout(()=>{
				uni.stopPullDownRefresh()
			},1000)
		},
		onReachBottom() {
			if(this.page<this.pageTotal){
				++this.page
				this.getAnswerList()
			}else{
				uni.showToast({
					title:'我也是有底线的',
					icon:'none'
				})
			}
		},
		onPageScroll(e) {
			// console.log('滚你懂',e.scrollTop,this.nodeScrollTop)
			if(e.scrollTop>=this.nodeScrollTop){
				this.canFixed=true
			}else{
				this.canFixed=false
			}
		}
	}
</script>

<style lang="scss" scoped>
@import "@/static/public.scss";
video{
	width: 100%;
}
.quesDetail{
	// padding: 30rpx 0 150rpx;
	padding: 0 0 150rpx;
	box-sizing: border-box;
	.aboutQues{
		padding:0 30rpx;
		box-sizing: border-box;
	}
	.quesTask{
		background: rgba(42,191, 212, .05);
		padding: 20rpx 10rpx;
		box-sizing: border-box;
		margin:20rpx 0 0;
		.topic{
			background: $colorlightorg;
			color: #fff;
			flex-shrink: 0;
			border-radius: 8rpx;
			width: 72rpx;
			text-align: center;
			height: 40rpx;
			line-height: 40rpx;
			margin:0 20rpx 0 0;
		}
	}
	.quesTitle{
		border-bottom: 1px dashed $bordercolor;
		padding: 30rpx 0;
		box-sizing: border-box;
		position: relative;
		.titleArea{
			margin:0 30rpx 0 0;
			image{
				width: 50rpx;
				height: 50rpx;
				vertical-align: middle;
				margin-top: -6rpx;
			}
			text{
				display: inline-block;
				vertical-align: middle;
				margin:-6rpx 10rpx 0 -8rpx;
			}
		}
		.del{
			flex-shrink: 0;
		}
	}
	.quesCon{
		margin-bottom: 40rpx;
		.quesTxt{
			margin:0 0 20rpx;
		}
	}
	.posTag{
		position: absolute;
		top:-40rpx;
		right: 0;
		text-align: center;
		image{
			width:60rpx;
			height: 60rpx;
		}
		text{
			display: inline-block;
			position: absolute;
			left:0;
			right: 0;
			bottom: 0;
			top: 0;
			margin: auto;
			line-height: 50rpx;
		}
	}
	.avatar{
		margin: 36rpx 0;
		position: relative;
		.quesAva{
			width:84rpx;
			height:84rpx;
			flex-shrink: 0;
			margin-right: 20rpx;
			position: relative;
			image{
				border-radius: 50%;
				width:100%;
				height:100%;
			}
			.focus{
				position: absolute;
				bottom: -10rpx;
				left: 15%;
				width: 70%;
				background: $colorred;
				border-radius: 20rpx;
				height: 35rpx;
				line-height: 35rpx;
				text-align: center;
				color: #fff;
				z-index: 10;
			}
		}
		// 与头像水平对齐的关注样式
		.focus{
			background: $colorred;
			color: #fff;
			padding:8rpx 20rpx;
			border-radius: 40rpx;
			text-align: center;
		}
		.bounty{
			image{
				width: 50rpx;
				height: 50rpx;
			}
			margin:0 0 0 30rpx;
		}
	}
	.bestAnswer{
		position: relative;
		border:20rpx solid $bordercolor;
		border-left: none;
		border-right: none;
		padding:30rpx;
		box-sizing: border-box;
		.bestTitle{
			border-bottom: 1px solid $bordercolor;
			&>view{
				position: relative;
				padding:0 0 30rpx;
				box-sizing: border-box;
			}
			&>view::after{
				content: '';
				display:block;
				position:absolute;
				height: 8rpx;
				width: 100%;
				left:0;
				bottom: 0;
				background:$colorMain;
				border-radius: 20rpx;
				box-shadow: 0 6rpx 10rpx rgba(0, 0, 0, .15);
			}
		}
		.noWidthBtn{
			height: 60rpx;
			line-height: 60rpx;
			padding: 0 10rpx;
			box-sizing: border-box;
			image{
				width:28rpx;
				height: 28rpx;
			}
		}
	}
	.answer{
		padding:0 30rpx;
		box-sizing: border-box;
		// margin: 24rpx 0;
		.answerTitle{
			position:relative;
			margin:0 0 30rpx;
			border-bottom: 1px solid $bordercolor;
		}
		.fixedTop{
			position: fixed;
			width: 100%;
			left:0;
			top: 0;
			background: rgba(255, 255, 255, 1);
			padding:175rpx 30rpx 0;
			box-sizing: border-box;
			z-index: 100;
			border-bottom: 1px solid $bordercolor;
		}
		.txt{
			display: inline-block;
			padding: 24rpx 0;
			position: relative;
			&::after{
				content:'';
				width: 100%;
				position: absolute;
				left:0;
				bottom: 0;
				background: $colorMain;
				height: 10rpx;
				border-radius: 20rpx;
				box-shadow: 0 6px 10px rgba(0,0,0,.15);
			}
		}
	}
	.answerAvatar{
		margin:40rpx 0 0;
		.quesAva{
			width:60rpx;
			height:60rpx;
			flex-shrink: 0;
			margin-right: 10rpx;
			position: relative;
			image{
				border-radius: 50%;
				width:100%;
				height:100%;
			}
			.focus{
				position: absolute;
				bottom: -10rpx;
				left: 15%;
				width: 70%;
				background: $colorred;
				border-radius: 20rpx;
				height: 35rpx;
				line-height: 35rpx;
				text-align: center;
				color: #fff;
				z-index: 10;
			}
		}
	}
	.fixBottom{
		position:fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		// padding: 30rpx 0;
		height: 100rpx;
		line-height: 100rpx;
		box-shadow: 0 0 10rpx 0 rgba(0,0,0,.15);
		background:#fff;
		z-index: 10;
		.line{
			width: 1px;
			height: 40rpx;
			background: $bordercolor;
		}
		.txt{
			line-height:initial;
		}
		cover-image{
			width: 40rpx;
			height: 40rpx;
			margin-right: 5rpx;
		}
	}
}
</style>
